﻿using DesktopClient.Properties;
using DesktopShare;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DesktopClient
{
    public partial class FormClient : Form
    {
        List<byte[]> TempImageData = new List<byte[]>();
        List<BroadcastItem> Items = new List<BroadcastItem>();
        public FormClient()
        {
            InitializeComponent();
            Load += FormClient_Load;
            pcScreen.AllowDrop = true;
        }

        private void FormClient_Load(object sender, EventArgs e)
        {
            var configs = ConfigItem.GetConfig();
            foreach (var item in configs)
            {
                Items.Add(new BroadcastItem(item.BroadcastAddress, item.BroadcastPort));
            }

            BindListData();
        }

        public void BindListData()
        {
            lstServers.DataSource = null;
            lstServers.DataSource = Items;
            lstServers.DisplayMember = "Key";
            lstServers.ValueMember = "Key";
        }

        private bool GetImage(MemoryStream ms, out Image image)
        {
            try
            {
                image = Image.FromStream(ms);
                return true;
            }
            catch
            {
                image = null;
                return false;
            }
        }

        private void WriteLog(string tag, string info)
        {
            if (!File.Exists("logs.txt"))
            {
                var fs = File.Create("logs.txt");
                fs.Close();
            }
            using (FileStream fs = new FileStream("logs.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
            {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                {
                    sw.WriteLine(tag + ": " + info);
                }
            }
        }

        private void tsClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void lstServers_MouseDown(object sender, MouseEventArgs e)
        {
            if (lstServers.Items.Count == 0 || lstServers.SelectedItem == null)
                return;
            var item = lstServers.SelectedItem as BroadcastItem;
            DoDragDrop(item.Key, DragDropEffects.All);
        }

        private void tlpMain_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }

        private void tlpMain_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.StringFormat))
            {
                var old = Items.FirstOrDefault(t => t.Key == (pcScreen.Tag == null ? "" : pcScreen.Tag.ToString()));
                if (old != null)
                    old.Socket.Stop();
                var key = (string)e.Data.GetData(DataFormats.StringFormat);
                pcScreen.Tag = key;
                var item = Items.FirstOrDefault(t => t.Key == key);
                if (item != null)
                {
                    if (item.Socket == null)
                    {
                        item.Socket = new BroadcastSocket(item.BroadcastAddress, item.BroadcastPort);
                    }
                    if (item.Socket.UdpReceive == null)
                    {
                        item.Socket.OnDataReceive += (d) =>
                        {
                            using (MemoryStream ms = new MemoryStream(d))
                            {
                                Image img = null;
                                GetImage(ms, out img);
                                if (img != null)
                                {
                                    pcScreen.Image = img;
                                }
                            }
                        };
                        item.Socket.Run();
                    }
                }
            }
        }

        private void tsShow_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            FormAdd add = new FormAdd(Items, BindListData);
            add.StartPosition = FormStartPosition.CenterScreen;
            add.ShowDialog();
        }
        bool isfull = false;
        FullScreenHelper helper;
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
        private void Pb_DoubleClick(object sender, EventArgs e)
        {
            var pic = sender as PictureBox;
            if (isfull == false)
            {
                pic.Dock = DockStyle.None;
                pic.Left = 0;
                pic.Top = 0;
                pic.Width = Screen.PrimaryScreen.WorkingArea.Width;
                pic.Height = Screen.PrimaryScreen.WorkingArea.Height;
                pic.Focus();// 获得焦点，否则也得不到按键
                SetParent(pic.Handle, IntPtr.Zero);
                isfull = true;
            }
            else
            {
                pic.Dock = DockStyle.Fill;
                SetParent(pic.Handle, splitContainer1.Panel2.Handle);
                isfull = false;
            }
        }
    }
}
